package com.cennavi.list;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Log extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4178274509719295091L;

	/**
	 * Constructor of the object.
	 */
	public Log() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS, DELETE,PUT");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		try {
			

			int row = Integer.parseInt(request.getParameter("row") ==null?"1000":request.getParameter("row"));
			
			List<String> rows = this.getLog(row);

			for(String r:rows)
				out.println(r);

		} catch (Exception e) {
			out.println("{\"error_code\":-1,\"error_msg\":\"" + e.getMessage()
					+ "\"}");
		} finally {
			out.flush();

			out.close();
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}
	
	public List<String> getLog(int row) throws Exception{
		Socket socket = new Socket("10.20.20.11",19000);
		
		OutputStream out = socket.getOutputStream();
		
		DataOutputStream dos = new DataOutputStream(out);
		
		dos.writeInt(row);
		
		
		List<String> list = new ArrayList<String>();
		
		Scanner scanner = new Scanner(socket.getInputStream());
		
		while(scanner.hasNextLine()){
			list.add(scanner.nextLine());
		}
		
		socket.close();
		
		return list;
	}

}
